const db = require("../../db");
const { v4: uuidv4 } = require("uuid");
const bcrypt = require("bcryptjs");
/**
 * POST 人员的回调函数
 * @param userName  人员名称
 * @param unitcode  人员代码
 * @param unitType  类型
 * @param remark  备注
 */
exports.add = (req, res) => {
  // 接收表单的数据
  const unitInfo = req.body;
  let sql = "select * from selection_user where userName=?";
  db.query(sql, [unitInfo.userName], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length > 0) {
      return res.cc("人员名称已被占用!");
    }
    const uniqueCode = uuidv4();
    let sql1 = "insert into selection_user set ?";
    db.query(
      sql1,
      {
        userName: unitInfo.userName,
        password: bcrypt.hashSync("12345678", 10),
        role: unitInfo.role,
        // userId: uniqueCode,
        remark: unitInfo.remark,
        unitId: unitInfo.unitId,
        unitName: unitInfo.unitName,
        createdTime: Date.now(), // 例如 createdTime 使用 Date.now() 来获取当前时间戳
      },
      (error, result) => {
        if (error) return res.cc(error);
        // 判断影响行数是否为 1
        if (result.affectedRows !== 1) return res.cc("新增人员失败！");
        return res.cc("新增人员成功", true);
      }
    );
  });
};

exports.del = (req, res) => {
  // 接收表单的数据
  const unitInfo = req.body;
  let sql = "select * from selection_user where userId=?";
  db.query(sql, [unitInfo.userId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    console.log("this1----", result);
    if (result.length === 0) {
      return res.cc("未找到该人员!");
    }
    // 定义 SQL 语句
    const sql1 = "delete from selection_user where userId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(sql1, unitInfo.userId, (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("删除人员失败！");
      return res.cc("删除人员成功", true);
    });
  });
};

exports.update = (req, res) => {
  // 接收表单的数据
  const unitInfo = req.body;
  let sql = "select * from selection_user where userId=?";
  db.query(sql, [unitInfo.userId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length === 0) {
      return res.cc("未找到该人员!");
    }
    // 定义 SQL 语句
    const sql1 =
      "update selection_user set userName=?, role=?, remark=?, unitName=?, unitId=? where userId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(
      sql1,
      [
        unitInfo.userName,
        unitInfo.role,
        unitInfo.remark,
        unitInfo.unitName,
        unitInfo.unitId,
        unitInfo.userId,
      ],
      (error, result) => {
        if (error) return res.cc(error);
        // 判断影响行数是否为 1
        if (result.affectedRows !== 1) return res.cc("修改人员失败！");
        return res.cc("修改人员成功", true);
      }
    );
  });
};

exports.allList = (req, res) => {
  const page = req.body.page ? parseInt(req.body.page) : 1; // Get the page number, default to the first page
  const limit = req.body.limit ? parseInt(req.body.limit) : 10; // Get the number of items per page, default to 10
  const userName = req.body.userName || ""; // Get userName from request body or set to an empty string
  const sqlCount =
    "SELECT COUNT(*) AS total FROM selection_user WHERE userName != 'admin'";
  db.query(sqlCount, (error, countResults) => {
    if (error) {
      return res.cc(error);
    }
    const total = countResults[0].total;
    const offset = (page - 1) * limit;
    let sql;
    let params;
    if (userName) {
      sql = `SELECT * FROM selection_user WHERE userName LIKE ? AND userName != 'admin' LIMIT ? OFFSET ?`;
      params = [`%${userName}%`, limit, offset];
    } else {
      sql = `SELECT * FROM selection_user WHERE userName != 'admin' LIMIT ? OFFSET ?`;
      params = [limit, offset];
    }
    db.query(sql, params, (error, results) => {
      if (error) {
        return res.cc(error);
      }
      return res.cc("获取人员成功", true, results, {
        total,
        page,
        limit,
      });
    });
  });
};

exports.updatePass = (req, res) => {
  // 接收表单的数据
  const unitInfo = req.body;
  let sql = "select * from selection_user where userId=?";
  db.query(sql, [unitInfo.userId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length === 0) {
      return res.cc("未找到该人员!");
    }
    const password = bcrypt.hashSync("12345678", 10);
    // 定义 SQL 语句
    const sql1 = "update selection_user set password=? where userId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(sql1, [password, unitInfo.userId], (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("重置密码失败！");
      return res.cc("重置密码成功", true);
    });
  });
};

exports.changePassword = (req, res) => {
  // 接收表单的数据
  const unitInfo = req.body;
  const newPassword = unitInfo.newPassword;
  let sql = "select * from selection_user where userId=?";
  db.query(sql, [unitInfo.userId], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    if (result.length === 0) {
      return res.cc("未找到该人员!");
    }
    const password = bcrypt.hashSync(newPassword, 10);
    // 定义 SQL 语句
    const sql1 = "update selection_user set password=? where userId=?";
    // 调用 db.query() 执行 sql 语句
    db.query(sql1, [password, unitInfo.userId], (error, result) => {
      if (error) return res.cc(error);
      // 判断影响行数是否为 1
      if (result.affectedRows !== 1) return res.cc("修改密码失败！");
      return res.cc("修改密码成功", true);
    });
  });
};

exports.getUserInfo = (req, res) => {
  const unitInfo = req.body;
  let sql = "select * from selection_user where userName=?";
  db.query(sql, [unitInfo.userName], (error, result) => {
    if (error) {
      return res.cc(error);
    }
    const user = {
      ...result[0], // 解构用户信息
      password: "", //密码等敏感信息置空
    };
    if (result.length === 0) {
      return res.cc("未找到该人员!");
    }
    return res.cc("获取人员信息成功", true, user);
  });
};
